import React, { FC } from "react";
import classnames from "classnames";
import { getInitStateValue, timeRangeFormat } from "../utils";
import { Datedirection, Datecalender, Dateclear } from "@ct0/icons";
import { prefixCls } from "../constant";
import type { DateTimeRangeProps } from "../type";

interface Props extends DateTimeRangeProps {
  onTrigger: () => void;
}

const DataTimeRangeTrigger: FC<Props> = ({
  onTrigger,
  onChange,
  value,
  disabled,
  disabledTime,
  label,
}) => {
  const curPrefix = `${prefixCls}-trigger`;
  const hasNoValue = !value || (!value[0] && !value[1]);
  const [start, end] = getInitStateValue(value);
  const onClear = (e: any) => {
    e.stopPropagation();
    if (disabled) {
      return;
    }
    onChange?.(null);
  };
  const onClick = () => {
    if (disabled) {
      return;
    }
    onTrigger();
  };
  const operationComponent = () => {
    if (disabled || hasNoValue) {
      return (
        <div className={`${curPrefix}-operation`}>
          <span
            className={classnames(
              `${curPrefix}-icon`,
              `${curPrefix}-calenderIcon`
            )}
          >
            <Datecalender />
          </span>
        </div>
      );
    }
    return (
      <div className={`${curPrefix}-operation`}>
        <span
          onClick={onClear}
          className={classnames(`${curPrefix}-icon`, `${curPrefix}-clearIcon`)}
          title="clear"
        >
          <Dateclear />
        </span>
        <span
          className={classnames(`${curPrefix}-icon`, `${curPrefix}-rangeIcon`)}
        >
          <Datecalender />
        </span>
      </div>
    );
  };
  const valueComponent = () => {
    if (hasNoValue) {
      return <span className={`${prefixCls}-text`} />;
    }
    return (
      <>
        <span className={`${prefixCls}-text`}>
          {timeRangeFormat(start, disabledTime)}
        </span>
        <span className={`${curPrefix}-separator`}>
          <Datedirection />
        </span>
        <span className={`${prefixCls}-text`}>
          {timeRangeFormat(end, disabledTime)}
        </span>
      </>
    );
  };
  const triggerLabel = label ?? "时间范围";
  return (
    <div
      className={classnames(`${curPrefix}`, {
        ["disabled"]: disabled,
      })}
      onClick={onClick}
      role="trigger"
    >
      <span className={`${curPrefix}-name`}>
        {triggerLabel ? `${triggerLabel}:` : ""}
      </span>
      {valueComponent()}
      {operationComponent()}
    </div>
  );
};

export default DataTimeRangeTrigger;
